﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Security.Cryptography;
using System.Web.Security;

namespace ReconUI
{
    public partial class UserMaster : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (((UserVO)Session["CurrentUserVO"]) == null)
            {
                Response.Redirect("ReconSignIn.aspx");
            }

            txtCustomerId.Text = ((UserVO)Session["CurrentUserVO"]).customerId;
            txtCustomerId.ReadOnly = true;
            if (!IsPostBack)
            {
                loadRoles();
                bntbrowse.Enabled = false;
                bntgetdetails.Enabled = false;
                txtPassword.Text = "";
                txtPassword.Enabled = true;
                rbOption.Focus();
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string resp = string.Empty;
            DBFactory db = new DBFactory();
            DataTable dtUserDetails = new DataTable();
            string role_id = "";
            string role_type = "";
            int is_Enabled = 0;
            int is_lock = 0;
            int is_Active = 0;
            int is_DomainUser = 0;
            string[] arr = new string[2];
            arr = ddlUserType.SelectedValue.ToString().Split('-');
            role_id = arr[1];
            role_type = arr[0];
            //if (ddlUserType.SelectedValue == "C")
            //    role_id = "Customer";
            //else if (ddlUserType.SelectedValue == "R")
            //    role_id = "Remitter";
            //else 
            //    role_id = "System";

            if(chkEnable.Checked)
                is_Enabled = 1;
            if(chkLock.Checked)
                is_lock = 1;
            if (chkActive.Checked)
                is_Active = 1;

            if (rbOption.SelectedValue == "1")
            {
                
                // `ModBy_UserId` int(10) unsigned default NULL,  `ModBy_Date` datetime default NULL,
                // `AuthBy_UserId` int(10) unsigned default NULL,  `AuthBy_Date` datetime default NULL,  
                //`` datetime default NULL,
                //`` bit(1) default NULL,

                        dtUserDetails = db.GetUserDetailsByUserId(Convert.ToString(txtUserId.Text.Trim()));

                        if (dtUserDetails.Rows.Count == 1)
                        {
                            //ClientScript.RegisterClientScriptBlock(this.GetType(), "SuccessMessage", "<script>alert('User already exist!')</script>");
                            lblMessage.Text = "User already exist!";
                            btnClickPopup.Show();
                        }
                        else
                        {
                            int retval = db.RegisterUser(txtUserId.Text, role_type, txtRemitterId.Value, txtCustomerId.Text, txtUserName.Text, txtPassword.Text, role_id, txtEmail.Text, txtMobileNumber.Text, is_Enabled, is_lock, is_Active, is_DomainUser, ((UserVO)Session["CurrentUserVO"]).userId);

                            if (retval != 0)
                            {
                                //ClientScript.RegisterClientScriptBlock(this.GetType(), "SuccessMessage", "<script>alert('User added successfully!')</script>");
                                lblMessage.Text = "User added successfully!";
                                btnClickPopup.Show();
                                ResetFields();
                            }
                            else
                            {
                                //ClientScript.RegisterClientScriptBlock(this.GetType(), "ErrorMessage", "<script>alert('Error adding user!')</script>");
                                lblMessage.Text = "Error adding user!";
                                btnClickPopup.Show();
                            }
                        }
            }
            else
            {


                dtUserDetails = db.GetUserDetailsByUserId(Convert.ToString(txtUserId.Text.Trim()));

                if (dtUserDetails.Rows.Count <= 0)
                {
                    //ClientScript.RegisterClientScriptBlock(this.GetType(), "SuccessMessage", "<script>alert('User does not exist!')</script>");
                    lblMessage.Text = "User does not exist!";
                    btnClickPopup.Show();
                }
                else if (dtUserDetails.Rows.Count == 1)
                {
                    if ((txtUserId.Text.Trim() != ((UserVO)Session["CurrentUserVO"]).userId))
                    {
                        int retval = db.ModifyUser(txtUserId.Text, role_type, txtRemitterId.Value, txtCustomerId.Text, txtUserName.Text, role_id, txtEmail.Text, txtMobileNumber.Text, is_Enabled, is_lock, is_Active, is_DomainUser, ((UserVO)Session["CurrentUserVO"]).userId);

                        if (retval != 0)
                        {
                            //ClientScript.RegisterClientScriptBlock(this.GetType(), "SuccessMessage", "<script>alert('User modified sucessfully!')</script>");
                            lblMessage.Text = "User modified sucessfully!";
                            btnClickPopup.Show();
                            ResetFields();
                        }
                        else
                        {
                            //ClientScript.RegisterClientScriptBlock(this.GetType(), "ErrorMessage", "<script>alert('Error Modifying user!')</script>");
                            lblMessage.Text = "Error Modifying user!";
                            btnClickPopup.Show();
                        }
                    }
                    else if ((txtUserId.Text.Trim() == ((UserVO)Session["CurrentUserVO"]).userId) && (is_Enabled != 0))
                    {
                        int retval = db.ModifyUser(txtUserId.Text, role_type, txtRemitterId.Value, txtCustomerId.Text, txtUserName.Text, role_id, txtEmail.Text, txtMobileNumber.Text, is_Enabled, is_lock, is_Active, is_DomainUser, ((UserVO)Session["CurrentUserVO"]).userId);

                        if (retval != 0)
                        {
                            //ClientScript.RegisterClientScriptBlock(this.GetType(), "SuccessMessage", "<script>alert('User modified sucessfully!')</script>");
                            lblMessage.Text = "User modified sucessfully!";
                            btnClickPopup.Show();
                            ResetFields();
                        }
                        else
                        {
                            //ClientScript.RegisterClientScriptBlock(this.GetType(), "ErrorMessage", "<script>alert('Error Modifying user!')</script>");
                            lblMessage.Text = "Error Modifying user!";
                            btnClickPopup.Show();
                        }
                    }
                    else
                    {
                        lblMessage.Text = "Cannot change logged in user!";
                        btnClickPopup.Show();
                    }
                }
            }



        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ResetFields();
        }

        private void ResetFields()
        {
            rbOption.SelectedValue = "1";
            bntgetdetails.Enabled = false;
            bntbrowse.Enabled = false;
            txtUserId.Text = "";
            ddlUserType.ClearSelection();
            ddlUserType.SelectedValue = "0";
            txtRemitterId.Value = "";
            txtCustomerId.Text = "";
            txtUserName.Text = "";
            txtPassword.Text = "";
            txtEmail.Text = "";
            txtMobileNumber.Text = "";
            chkEnable.Checked = true;
            chkActive.Checked = true;
            chkLock.Checked = false;
        }

        //protected void imgbtnSearch_Click(object sender, ImageClickEventArgs e)
        //{
        //    Session["UserSearch"] = txtUserId.Text.ToString().Trim();
        //    ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<SCRIPT>window.open('SearchUser.aspx', '_Parent', 'height=400, width=650, left=300, top=150, location=no, menubar=no, resizable=no,scrollbars=no, titlebar=no, toolbar=no',false);</SCRIPT>");
        //}

        protected void btnGetUserDetails_Click(object sender, EventArgs e)
        {
           
                  
        }

        protected void bntgetdetails_Click(object sender, EventArgs e)
        {
            DataTable dtUserDetails = new DataTable();
            DBFactory objDBfactory = new DBFactory();

            try
            {

                if (txtUserId.Text.Trim() != "")
                    {
                        dtUserDetails = objDBfactory.GetUserDetailsByUserId(Convert.ToString(txtUserId.Text.Trim()));

                        if ((dtUserDetails) == null)
                        {
                            //ClientScript.RegisterClientScriptBlock(this.GetType(), "SuccessMessage", "<script>alert('No record found for this user!')</script>");
                            lblMessage.Text = "No record found for this user!";
                            btnClickPopup.Show();
                        }
                        else if (dtUserDetails.Rows.Count == 1)
                        {
                            ResetFields();
                            
                            //if (dtUserDetails.Rows[0].ItemArray[1].ToString() == "C")
                            //{
                            //    ddlUserType.ClearSelection();
                            //    ddlUserType.Items.FindByValue("C").Selected = true;
                            //}
                            //else if (dtUserDetails.Rows[0].ItemArray[1].ToString() == "R")
                            //{
                            //    ddlUserType.ClearSelection();
                            //    ddlUserType.Items.FindByValue("R").Selected = true;
                            //}
                            //else if (dtUserDetails.Rows[0].ItemArray[1].ToString() == "S")
                            //{
                            //    ddlUserType.ClearSelection();
                            //    ddlUserType.Items.FindByValue("S").Selected = true;
                            //}

                            ddlUserType.ClearSelection();
                            ddlUserType.Items.FindByValue(dtUserDetails.Rows[0].ItemArray[1].ToString() + "-" + dtUserDetails.Rows[0].ItemArray[6].ToString()).Selected = true;

                            txtUserId.Text = dtUserDetails.Rows[0].ItemArray[0].ToString();
                            txtRemitterId.Value = dtUserDetails.Rows[0].ItemArray[2].ToString();
                            txtCustomerId.Text = dtUserDetails.Rows[0].ItemArray[3].ToString();
                            txtUserName.Text = dtUserDetails.Rows[0].ItemArray[4].ToString();
                            //txtPassword.Text = dtUserDetails.Rows[0].ItemArray[5].ToString();
                            txtEmail.Text = dtUserDetails.Rows[0].ItemArray[7].ToString();
                            txtMobileNumber.Text = dtUserDetails.Rows[0].ItemArray[8].ToString();
                            if (dtUserDetails.Rows[0].ItemArray[9].ToString() == "True")
                                chkEnable.Checked = true;
                            else
                                chkEnable.Checked = false;
                            if (dtUserDetails.Rows[0].ItemArray[10].ToString() == "True")
                                chkLock.Checked = true;
                            else
                                chkLock.Checked = false;
                            if (dtUserDetails.Rows[0].ItemArray[11].ToString() == "True")
                                chkActive.Checked = true;
                            else
                                chkActive.Checked = false;

                            rbOption.SelectedValue = "2";
                    
                        }
                        else
                        {
                            //ClientScript.RegisterClientScriptBlock(this.GetType(), "SuccessMessage", "<script>alert('No record found for this user!')</script>");
                            lblMessage.Text = "No record found for this user!";
                            btnClickPopup.Show();
                        }
                 }
                else
                {
                    //ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Enter User ID!')</script>");
                    lblMessage.Text = "Enter User ID!";
                    btnClickPopup.Show();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if ((dtUserDetails) != null)
                {
                    dtUserDetails.Dispose();
                }
                dtUserDetails = null;

            }

                
        }

        protected void bntbrowse_Click(object sender, EventArgs e)
        {
            string path;
            path = "UserMaster.aspx";
            // txtUserId.Text - Get the value ctl00$BodyHolder$txtUserId from Unique Id of the control txtUserId
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<SCRIPT>window.open('SearchUser.aspx?textbox=" + txtUserId.Text  + "&PageRequest= " + path + "','cal','height=400, width=650, left=300, top=150, location=no, menubar=no, resizable=no,scrollbars=no, titlebar=no, toolbar=no',false);</SCRIPT>");
        }

        protected void btnok_Click(object sender, EventArgs e)
        {
            btnClickPopup.Hide();
        }

        protected void rbOption_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rbOption.SelectedValue.Trim() == "1")
            {
                bntbrowse.Enabled = false;
                bntgetdetails.Enabled = false;
                txtPassword.Text = "";
                txtPassword.Enabled = true;
            }
           else 
            {
                bntbrowse.Enabled     = true;
                bntgetdetails.Enabled = true;
                txtPassword.Text = "";
                txtPassword.Enabled = false;
            }
        }

        protected void bntbrowseRemitter_Click(object sender, EventArgs e)
        {
            string path;
            path = "UserMaster.aspx";
            // txtUserId.Text - Get the value ctl00$BodyHolder$txtUserId from Unique Id of the control txtUserId
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<SCRIPT>window.open('SearchRemitter.aspx?textbox=" + txtRemitterId.Value + "&PageRequest= " + path + "','cal','height=400, width=650, left=300, top=150, location=no, menubar=no, resizable=no,scrollbars=no, titlebar=no, toolbar=no',false);</SCRIPT>");
        }

        private void loadRoles()
        {
            DBFactory db = new DBFactory();
            DataTable dtRole = null;
            try
            {
                dtRole = db.GetAllRoles();

                if (dtRole != null && dtRole.Rows.Count > 0)
                {
                    ddlUserType.Items.Insert(0, "Select Role Type");
                    ddlUserType.Items[0].Value = "0";

                    for (int i = 0; i < dtRole.Rows.Count; i++)
                    {
                        ddlUserType.Items.Add(dtRole.Rows[i].ItemArray[2].ToString().Trim());
                        ddlUserType.Items[i + 1].Value = (dtRole.Rows[i].ItemArray[3].ToString().Trim() + "-" + dtRole.Rows[i].ItemArray[0].ToString().Trim());//Role_Id,Role_Code,Role_Desc,Role_Type
                    }
                }

            }
            catch (Exception ex)
            {

            }
            finally
            {
                if (dtRole != null)
                {
                    dtRole.Dispose();
                }
                dtRole = null;
                db = null;
            }

        }

        protected void onSelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList obj = (DropDownList)sender;
            string value = obj.SelectedValue;
            if (value.Equals("Remitter"))
            {
                bntbrowseRemitter.Enabled = true;
            }
            else
            {
                bntbrowseRemitter.Enabled = false;
            }
        }
    }
}